<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category AuthorizationsController.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/3/3  18:12
 * +--------------------------------------------------------+
 */

namespace App\Http\Controllers\Admin\V1;


use App\Services\AdminService;
use App\Services\MyStockService;
use App\Services\Swoole\WebSocketClient;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AuthorizationsController extends Controller
{
    /**
     * @var
     */
    protected $adminService;
    protected $myStockService;

    public function __construct(AdminService $adminService, MyStockService $myStockService)
    {
        $this->adminService = $adminService;

        $this->myStockService = $myStockService;

        $this->middleware('auth:admin', ['only' => ['getInfo']]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     * @Depiction 登录
     * @Author hwy <429208948@qq.com>
     * @Date 2022/1/7  15:26
     */
    public function store(Request $request)
    {
        $rules      = [
            'username' => 'required|string|between:6,32',
            'password' => 'required|string|between:6,32',
        ];
        $attributes = [
            'username' => '用户名',
            'password' => '密码',
        ];
        $messages   = [];

        $this->validate($request, $rules, $messages, $attributes);

        $credentials['mobile']   = $request->username;
        $credentials['password'] = $request->password;

        // if (!$token = $this->jwt->attempt($credentials)) {
        if (!$token = auth('admin')->attempt($credentials)) {
            return $this->responseErrorData('账号和密码错误!');
        }

        $data['access_token'] = $token;
        $data['token_type']   = 'Bearer';
        $data['expires_in']   = config('jwt.ttl') * 60;
        return $this->responseSuccessData('登录成功!', $data);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @Depiction 刷新token
     * @Author hwy <429208948@qq.com>
     * @Date 2022/1/7  17:33
     */
    public function update()
    {
        // $old_token = $this->jwt->getToken();
        // $token = $this->jwt->refresh($old_token);
        $token = auth('admin')->refresh();

        $data['access_token'] = $token;
        $data['token_type']   = 'Bearer';
        $data['expires_in']   = config('jwt.ttl') * 60;
        return $this->responseSuccessData('刷新成功!', $data);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @Depiction 退出，摧毁token
     * @Author hwy <429208948@qq.com>
     * @Date 2022/1/7  17:33
     */
    public function destroy()
    {
        // $data = auth('api')->invalidate(true);
        $data = auth('admin')->logout(true);
        return $this->responseSuccessData('退出成功!', $data);
    }
}
